import {
  createCategory,
  deleteCategory,
  getCategoryList,
  updateCategory,
  moveCategory,
  moveSecCategory,
} from '@/services/category';
import {
  BranchesOutlined, CheckOutlined,
  CopyFilled,
  DeleteOutlined,
  DownOutlined,
  EditOutlined, MinusOutlined, MinusSquareOutlined, PartitionOutlined,
  PlusOutlined, UndoOutlined,
  UpOutlined
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import {Alert, Button, Card, Form, message, Modal, Radio, Space, Table} from 'antd';
import React, { useEffect, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import './index.less';
import {useModel} from "@@/plugin-model/useModel";
import ProForm, {ProFormSelect, ProFormText} from "@ant-design/pro-form";
import {moveTopic} from "@/services/topic";
import TreeItem from "@/components/TreeSide/treeItem";
import {HOMEPAGE_URL} from "../../../../proxyConfig";

const TableList: React.FC = (props) => {
  const [moveModal, setMoveModal] = useState(false);
  const [moveObj, setMoveObj] = useState({});
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [form] = Form.useForm();
  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [treeData, setTreeData] = useState([]);

  const changeTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      element.key = element.id;
      element.title = element.name;
      if (element.children && element.children.length > 0) {
        changeTreeData(element.children);
      }
    }
    return data;
  };

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      const params = {
        ...fields,
        type: 'topic',
        roleId: currentUser?.roleId,

      };
      if (!!addRow) {
        params.parentId = addRow.id;
      }
      const res = await createCategory(params);
      if (res.code == '0') {
        message.success('添加成功！');
      }
      await getCategory();
      return true;
    } catch (error) {
      message.error('添加失败!');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const params = {
      ...fields,
      id: currentRow.id,
      // parentId: currentRow.parentId,
      type: 'topic',
    };
    try {
      const res = await updateCategory(params);
      if (res.code == '0') {
        message.success('更新成功！');
      }
      await getCategory();
      return true;
    } catch (error) {
      message.error('更新失败！');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record) => {
    try {
      const res = await deleteCategory({
        id: record.id,
      });
      if (res.code == '0') {
        message.success('已删除！');
      }
      await getCategory();
      return true;
    } catch (error) {
      message.error('删除失败！'+ error.response.data.message);
      return false;
    }
  };
  const [delCurrentRow,setDelRow] = useState()
  const [delModalShow,setDelShow] = useState(false)
  const showDeleteModal = (e,type)=>{
    setDelRow(e)
    if(type =='parent'){
      const index = treeData.findIndex(i=>i.id == e.id)
      treeData.splice(index,1)
    }else{
      treeData.map(i=>{
        if (i.id == e.parentId) {
          const index = i.children.findIndex(i=>i.id == e.id)
          i.children.splice(index,1)
        }
        return i
      })
    }
    setDelShow(true)
  }

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<any>();

  const [addRow, setAddRow] = useState<any>();

  const [data, setData] = useState([]);

  const [isAdd, setIsAdd] = useState<boolean>(true);
  //查询分类
  //查询分类
  const getCategory = () => {
    const params = {
      type: 'topic',
      roleId: currentUser?.roleId,
    };
    //获取组list
    getCategoryList(params).then(async (res) => {
      setData(res.data);
      const data = changeTreeData(res.data);

      setTreeData(data);
    });
  };
  useEffect(() => {
    getCategory();
  }, []);
  const [value, setValue] = useState('');
  const copyTextToClipboard = (text)=> {
    if (navigator.clipboard) {
      // 现代浏览器使用异步Clipboard API
      navigator.clipboard.writeText(text).then(function() {
        message.success('复制成功');
      }).catch(function(error) {
        message.error('复制失败:'+ error);
      });
    } else {
      // IE8 使用document.execCommand()方法
      var textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select(); // 选中文本

      try {
        var successful = document.execCommand('copy');
        if (successful) {
          message.success('复制成功');
        } else {
          message.success('复制失败');
        }
      } catch (err) {
        message.error('复制失败:'+err);
      }

      document.body.removeChild(textArea); // 移除临时创建的textarea
    }
  };

  const onChange = (e: any) => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };

  const moveOut = (record) => {
    setMoveModal(true);
    setMoveObj(record);
    setValue(record.parentId);
  };
  //移动分类
  const moveAction = async (id, operation,flg,seq) => {
    if(flg&&flg=='parent' && seq && seq==2 && operation == 'up'){
      return
    }
    const res = await moveCategory({
      id,
      operation,
    });
    if (res.code == '0') {
      message.success('移动成功！');
      getCategory();
    }
  };
  const columns: any = [
    {
      title: '类别名称',
      dataIndex: 'name',
      key: 'name',
      width: '50%',
      render: (_, record) => {
        if (!record.parentId) {
          return (
            <div className="centerTableName">

              <div className="left">
                {
                  !record.children ?
                    <span style={{marginRight:'10px'}}>
                      <MinusOutlined />
                    </span>
                    : null
                }

                {record.name}
              </div>

              <div
                className="right"
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setAddRow(record);
                }}
              >
                <Button shape={'round'} icon={<PlusOutlined />}>
                  添加子类
                </Button>

              </div>
            </div>
          );
        } else {
          return <div className="left">
            <span style={{marginRight:'10px'}}>
              <PartitionOutlined />
            </span>
            {record.name}
          </div>;
        }
      },
    },
    {
      title: '操作',
      align: 'left',
      dataIndex: 'option',
      width: '50%',
      render: (_, record) => {
        if (!record.parentId) {
          return (
            <Space>

              <a
                style={{ color: '#1677ff' }}
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setCurrentRow(record);
                  setIsAdd(false);
                }}
              >
                <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
                  编辑
                </Button>
              </a>
              <a onClick={() => moveAction(record.id, 'up','parent',record.seq)}>
                <Button shape={'round'} icon={<UpOutlined />}>
                  上移
                </Button>
              </a>
              <a onClick={() => moveAction(record.id, 'down','parent')}>
                <Button shape={'round'} icon={<DownOutlined />}>
                  下移
                </Button>
              </a>
              <a
                style={{ color: 'red' }}
                onClick={() => {
                  showDeleteModal(record,'parent');
                }}
              >
                <Button danger shape={'round'} icon={<DeleteOutlined />}>
                  删除
              </Button>
              </a>
              <a onClick={() => {
                let url = HOMEPAGE_URL
                /*部署特勤局时需要修改内容*/
                console.log(record.id == 'a8779dd7-5b2e-4517-9286-5fa2bd3d1040');
                if(record.id == 'a8779dd7-5b2e-4517-9286-5fa2bd3d1040'){
                  url+='pages/monthStar/index.html?classify='+record.id+'&name='+record.name
                }else{
                  url+='pages/morePage/index.html?id='+record.id+'&name='+record.name
                }
                copyTextToClipboard(url)
              }}>
                <Button shape={'round'} icon={<CopyFilled/>}>
                  复制链接
                </Button>
              </a>
            </Space>
          );
        } else {
          return (
            <Space>
              <a
                style={{ color: '#1677ff' }}
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setCurrentRow(record);
                  setIsAdd(false);
                }}
              >
                <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
                  编辑
                </Button>
              </a>
              <a
                style={{ color: 'red' }}
                onClick={() => {
                  showDeleteModal(record,'child');
                }}
              >
                <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
                  删除
                </Button>
              </a>
              <a onClick={() => moveAction(record.id, 'up')}>
                <UpOutlined />上移
              </a>
              <a onClick={() => moveAction(record.id, 'down')}>
                <DownOutlined />下移
              </a>
              <a onClick={() => moveOut(record, 'up')}>
                <BranchesOutlined />移动
              </a>
              <a onClick={() => {
                let url = HOMEPAGE_URL
                /*部署特勤局时需要修改内容*/
                console.log(record.id == 'a8779dd7-5b2e-4517-9286-5fa2bd3d1040');
                if(record.id == 'a8779dd7-5b2e-4517-9286-5fa2bd3d1040'){
                  url+='pages/monthStar/index.html?classify='+record.id+'&name='+record.name
                }else{
                  url+='pages/morePage/index.html?id='+record.id+'&name='+record.name
                }
                copyTextToClipboard(url)
              }}>
                <Button shape={'round'} icon={<CopyFilled/>}>
                  复制链接
                </Button>
              </a>
            </Space>
          );
        }
      },
    },
  ];

  const [lbxz, setLbxz] = useState({});

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <Card title="">
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleUpdateModalVisible(true);
              setIsAdd(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined />
            添加
          </Button>
          <Table columns={columns} dataSource={data} rowKey={'id'} />
        </Space>
      </Card>
      <UpdateForm
        addType={isAdd}
        onSubmit={async (value) => {
          console.log({...currentRow,...value},'submit');
          //判断id是否存在，判断新建/边界
          let success;
          if (isAdd) {
            success = await handleAdd(value);
          } else {
            success = await handleUpdate(value);
          }
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
        key={new Date().getTime()}
      />
      <Modal
        open={moveModal}
        title="移动"
        destroyOnClose
        onOk={async () => {
          const params = {
            priId: value,
            secId: moveObj.id,
          };
          const res = await moveSecCategory(params);
          if (res.code == '0') {
            message.success('移动成功');
            setMoveModal(false);
            getCategory();
            setMoveObj({});
            setValue('');
          }
        }}
        onCancel={() => {
          setMoveModal(false);
          setMoveObj({});
        }}
      >
        <Radio.Group onChange={onChange} value={value}>
          <Space direction="vertical">
            {data.map((item) => {
              return (
                <Radio value={item.id} key={item.id} disabled={moveObj.parentId == item.id}>
                  {item.name}
                </Radio>
              );
            })}
          </Space>
        </Radio.Group>
      </Modal>

      <Modal
        title='当前目录文章移动至'
        width="600px"
        destroyOnClose
        open={delModalShow}
        onCancel={()=>{setDelShow(false);
          setDelRow({});}}
        footer={null}
      >
        <ProForm
          form={form}
          layout="horizontal"
          {...formLayout}
          initialValues={''}
          onFinish={async (value)=>{
            let params = {}
              params = {
                id: delCurrentRow.id,
                targetId: lbxz.id,
              };
            if(params.targetId){
              await moveTopic(params)
            }
             const res = await handleRemove(delCurrentRow)
            console.log(res);
            if(res.code == 0){
                message.success('操作成功！');
                await getCategory();
              }

            setDelShow(false);
            setDelRow({});
          }}
          onReset={() => {
            setDelShow(false);
            setDelRow({});
          }}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />取消</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}

                </Space>
              </div>
            ),
          }}
        >
          <Alert style={{marginBottom:'10px'}}  message="注意！若未选择栏目，文章则会被一起删除，无法恢复，谨慎操作！" type="error" />

          <TreeItem defaultData={treeData} multiple={false} setSelectedTreeData={setLbxz} />
       {/*   <ProFormSelect
            width="md"
            label="转移栏目"
            name="id"
            placeholder="请选择"
            request={async () => {
              // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
              // 如果需要转化参数可以在这里进行修改
              const msg = await getCategoryList({type: 'topic'})
              let res = [];
              msg.data.map((item) => {
                  let temp = {};
                  temp['label'] = item.name;
                  temp['value'] = item.id;
                  res.push(temp);
              });
              return res;
            }}
          />*/}
        </ProForm>
      </Modal>

    </PageContainer>
  );
};

export default TableList;
